<!-- 用户列表 -->
<template>
   <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图区 -->
        <el-card class="box-card">
            <!-- 搜索与添加区域 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>

            <!-- 用户列表区 -->
            <el-table
                :data="userList"
                border
                stripe>
                <el-table-column label="#" type="index" ></el-table-column>
                <el-table-column label="姓名" prop="username" ></el-table-column>
                <el-table-column label="邮箱" prop="email" ></el-table-column>
                <el-table-column label="电话" prop="mobile" ></el-table-column>
                <el-table-column label="角色" prop="role_name" ></el-table-column>
                <el-table-column label="状态" prop="mg_state" >
                    <!-- 作用域插槽 -->
                    <template slot-scope="scope">
                        <!-- 状态 -->
                        <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180px">
                    <!-- 作用域插槽 -->
                    <template slot-scope="scope">
                        <!-- 修改 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showModifyUserDialog(scope.row.id)"></el-button>
                        <!-- 删除 -->
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="showdeleteDialog(scope.row.id)"></el-button>
                        <!-- 分配角色 -->
                        <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页显示区 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[1, 2, 6, 8]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加用户的对话框 -->
        <el-dialog
            title="添加用户"
            :visible.sync="dialogVisible"
            width="50%"
            @close="dialogClose">
            <!-- 内容主体区 -->
            <el-form 
                :model="addForm" 
                :rules="addFormRules" 
                ref="addFormRef" 
                label-width="100px">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
                <el-input v-model="addForm.mobile"></el-input>
            </el-form-item>
            </el-form>
            <!-- 底部区 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改用户信息的对话框 -->
        <el-dialog
            title="修改用户信息"
            :visible.sync="modifyUserDialogVisible"
            width="50%"
            @close="modifyUserDialogClose">
            <!-- 内容主体区 -->
            <el-form 
                :model="modifyForm" 
                :rules="addFormRules" 
                ref="modifyFormRef" 
                label-width="70px">
            <el-form-item label="用户名">
                <el-input v-model="modifyForm.username" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="modifyForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
                <el-input v-model="modifyForm.mobile"></el-input>
            </el-form-item>
            </el-form>
            <!-- 底部区 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="modifyUserDialogVisible=false">取 消</el-button>
                <el-button type="primary" @click="modifyUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 删除用户的对话框 -->
        <el-dialog
            title="提示"
            :visible.sync="deleteDialogVisible"
            width="30%">
        <span><i class="el-icon-warning"></i> 此操作将永久删除该用户，是否继续？</span>
        <span slot="footer" class="dialog-footer">
            <el-button @click="deleteDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="deleteDialog">确 定</el-button>
        </span>
        </el-dialog>
   </div>
   
</template>

<script>
    export default {
        name: '',
        data () {
            // 验证邮箱的规则
            var checkEmail = (rule, value, cb) => {
                // 验证邮箱的正则表达式
                const regEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
                if (regEmail.test(value)){
                    return cb()
                }
                cb(new Error('请输入合法的邮箱'))
            }
            // 验证手机号的规则
            var checkMobile = (rule, value, cb) => {
                // 验证邮箱的正则表达式
                const regMobile = /^1(3|4|5|6|7|8|9)\d{9}$/
                if (regMobile.test(value)){
                    return cb()
                }
                cb(new Error('请输入合法的手机号'))
            }
            return {
                // 获取用户列表的参数对象
                queryInfo: {
                    // 搜索内容
                    query: '',
                    // 当前是第几页
                    pagenum: 1,
                    // 每页显示数量
                    pagesize: 2
                },
                userList: [],
                // 条数
                total: 0,
                // 添加用户对话框
                dialogVisible: false,
                // 添加用户的表单数据
                addForm: {},
                // 添加用户的表单数据规则
                addFormRules: {
                    // 用户名的规则
                    username: [
                        {
                            required: true,
                            message: '请输入用户名',
                            trigger: 'blur' // 失去焦点时触发
                        },
                        {
                            min: 3,
                            max: 10,
                            message: '用户名的长度在3到10位',
                            trigger: 'blur'
                        }
                    ],
                    // 密码的规则
                    password: [
                        {
                            required: true,
                            message: '请输入密码',
                            trigger: 'blur' // 失去焦点时触发
                        },
                        {
                            min: 6,
                            max: 15,
                            message: '密码的长度在6到15位',
                            trigger: 'blur'
                        }
                    ],
                    // 邮箱的规则
                    email: [
                        {
                            required: true,
                            message: '请输入邮箱',
                            trigger: 'blur' // 失去焦点时触发
                        },
                        {
                            validator: checkEmail,
                            trigger: 'blur'
                        }
                    ],
                    // 手机号码的规则
                    mobile: [
                        {
                            required: true,
                            message: '请输入手机号',
                            trigger: 'blur' // 失去焦点时触发
                        },
                        {
                            validator: checkMobile,
                            trigger: 'blur'
                        }
                    ]
                },
                // 修改用户对话框
                modifyUserDialogVisible: false,
                // 修改用户信息的表单数据
                modifyForm: {},
                // 删除用户的对话框
                deleteDialogVisible: false,
                // 删除用户的表单数据
                deleteForm: {},
            };
        },
        created(){
            this.getUserList()
        },
        methods: {
            // 从后台获取用户列表
            getUserList: async function() {
                const {data: res} = await this.$http.get('users', {params: this.queryInfo })
                if (res.meta.status !== 200) {
                    return this.$message.error("获取用户列表失败!")
                }
                this.userList = res.data.users
                this.total = res.data.total
            },
            // 改变每页显示数量
            handleSizeChange: function(newPageSize) {
                this.queryInfo.pagesize = newPageSize
                this.getUserList()
            },
            // 选择第几页
            handleCurrentChange: function(newPage) {
                this.queryInfo.pagenum = newPage
                this.getUserList()
            },
            // 更新状态的提示信息
            userStateChanged: async function(userinfo) {
                console.log(userinfo);
                const {data: res} = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
                if (res.meta.status !== 200) {
                    userinfo.mg_state = !userinfo.mg_state
                    return this.$message.error("更新用户状态失败")
                }
                this.$message.success("更新用户状态成功")
            },
            // 关闭对话框后清空表单
            dialogClose: function() {
                this.$refs.addFormRef.resetFields()
            },
            // 添加用户
            addUser: function() {
                this.$refs.addFormRef.validate(async valid => {
                    console.log("验证结果："+valid);
                    if(valid===false){
                        return this.$message.error('添加失败')
                    }
                    // 可以发起添加用户的网络请求
                    const{data:res} = await this.$http.post('users', this.addForm)
                    if(res.meta.status !== 201){
                        this.$message.error('添加失败')
                    }
                    this.$message.success('添加成功')
                    // 隐藏对话框
                    this.dialogVisible = false
                    // 重新加载用户列表
                    this.getUserList()
                })
            },
            // 显示修改用户对话框
            showModifyUserDialog: async function(id) {
                const{data:res} = await this.$http.get('users/'+ id )
                if(res.meta.status !== 200) {
                    return this.$message.error('查询用户信息失败')
                }
                this.modifyForm = res.data
                this.modifyUserDialogVisible = true
            },
            // 修改用户
            modifyUser: function() {
                this.$refs.modifyFormRef.validate(async valid => {
                    console.log("验证结果："+valid);
                    if(valid===false){
                        return this.$message.error('修改失败')
                    }
                    // 可以发起修改用户的网络请求
                    const{data:res} = await this.$http.put(`users/${this.modifyForm.id}`, this.modifyForm)
                    if(res.meta.status !== 200){
                        this.$message.error('修改失败')
                    }
                    // 隐藏对话框
                    this.modifyUserDialogVisible = false
                    // 重新加载用户列表
                    this.getUserList()
                    this.$message.success('修改成功')
                })
            },
            // 关闭修改用户对话框后重置表单
            modifyUserDialogClose: function() {
                this.refs.modifyFormRef.resetFields()
            },
            // 显示删除用户对话框
            showdeleteDialog: async function(id){
                const{data:res} = await this.$http.get('users/'+ id )
                if(res.meta.status !== 200) {
                    return this.$message.error('查询用户信息失败')
                }
                this.deleteForm = res.data
                this.deleteDialogVisible = true

            },
            // 删除用户
            deleteDialog: async function() {
                const{data:res} = await this.$http.delete(`users/${this.deleteForm.id}`)
                if(res.meta.status !== 200) {
                    return this.$message.error('删除失败')
                }
                // 重新加载用户列表
                this.getUserList()
                this.deleteDialogVisible = false
                this.$message.success('删除成功')
            }
        }
    }

</script>
<style lang='less' scoped>
</style>